/*
 * PC_Communication.c
 *
 *  Created on: 2016-5-21
 *      Author: Mahome
 */

// This Thread is used to Receive and Send the data
#include "BSW_Include.h"

ubyte SendBuf[Big_SIZE];
int8_t USBRxBuf[Big_SIZE];

void PC_Communication(void)
{
	uword NumBytes = 0;
	if(USBD_VCOM_IsEnumDone()&&(USB_DeviceState==DEVICE_STATE_Configured))		//USB was connected
	{
		PC.USBlink= Connceted;
		PC.OnUsing = USB;
		PC.USB_PreState = DEVICE_STATE_Configured;

		// Check number of bytes received
		NumBytes = (int16_t)USBD_VCOM_BytesReceived();
		USBD_VCOM_ReceiveData(&USBRxBuf[0],NumBytes);
		for(uword i=0;i<NumBytes;i++)
		{
			Enqueue(&USBRx,USBRxBuf[i]);
		}
		/*****upload response **************************/
		uword Bytes = 0;

		while(!IsEmpty(&StmTx))	// 每次调用将buf中的数据全部发送完成
		{
			SendBuf[Bytes++] = Dequeue(&StmTx);
			if(Bytes == 1)
				SEGGER_RTT_printf(0,"Upload Data:");
			SEGGER_RTT_printf(0,"%02X ",SendBuf[Bytes-1]);
		}


		if(Bytes!=0)
		{
			SEGGER_RTT_printf(0,"\r\n ");
			USBD_VCOM_SendData((const char *)SendBuf, Bytes);
		}
		if(!cellularNetworkConnectState())//
			PC.Celllink= NotConnected;
		return;
	}
	else if(cellularNetworkConnectState())//
	{
		PC.Celllink= Connceted;
		PC.OnUsing = Cellular;

		if(!cellularNetworkConnectState())//
			PC.Celllink= NotConnected;
		return;
	}
	else
	{
		if (PC.USB_PreState == DEVICE_STATE_Configured)
		{
			osDelay(20);
			status_t status;
			status = USBD_VCOM_Init();
			PC.USB_PreState = USB_DeviceState;
			SEGGER_RTT_printf(0,"Reset System!!! = %d\r\n",status);
		}
		PC.USBlink = NotConnected;
		PC.OnUsing = NoConnection;
	}
	CDC_Device_USBTask(&USBD_VCOM_CDCInterface);
}
